package com.example.easybuy.service;

import com.alibaba.fastjson.JSONObject;
import com.example.easybuy.dao.IndexDao;
import com.example.easybuy.pojo.Products;
import com.example.easybuy.pojo.ProductsManage;
import com.example.easybuy.pojo.SolrPage;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ProductsServiceImpl implements ProductsService {
    private Logger logger = Logger.getLogger(ProductsServiceImpl.class);
    @Autowired
    private IndexDao indexDao;

//    redis配置类
    @Autowired
    private RedisTemplate redisTemplate;

    //Solr操作类，里面提供了增删查的方法
    @Autowired
    private SolrClient solrClient;

    /**
     * 把所有产品查出来
     * 添加在solr里
     *
     * @return
     */
    @Override
    public List<Products> addProducts() throws IOException, SolrServerException {
        logger.debug("ProductsServiceImpl addProducts start......");
        List<Products> productsList = null;
        try {
            productsList = indexDao.proList();
            logger.debug("ProductsServiceImpl addProducts result: " + productsList);
            UpdateResponse updateResponse = solrClient.addBeans(productsList);
            logger.debug("ProductsServiceImpl addProducts result: " + productsList + " updateResponse: " + updateResponse);
            if (updateResponse.getStatus() != 0) {
                logger.debug("ProductsServiceImpl addProducts result: " + productsList + " updateResponse: " + updateResponse + " is error ");
                solrClient.rollback();
            }
//            提交的时候会阻塞线程，第一false和第二个false是不等待放行阻塞
            solrClient.commit(false, false, true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("ProductsServiceImpl addProducts is error ", e);
            solrClient.rollback();
        }
        return productsList;
    }


    /**
     * 模糊查询
     * 根据三级分类id查
     * 查询所有
     * @param name
     * @param classifythree
     * @param currentPage
     * @return
     */
    @Override
    public SolrPage<Products> proList(String name,String classifythree,String classifyone,String currentPage) {
        logger.debug("ProductsServiceImpl proList name: "+name+" classifythree "+classifythree+" classifyone: "+classifyone+" currentPage："+currentPage);
        SolrPage<Products> page=new SolrPage<Products>();
        SolrQuery query=new SolrQuery();

        QueryResponse qr = null;
        List<Products> pageCount=null;
        List<Products> proList=null;
        try {
            // 模糊查询
            if (!StringUtils.isEmpty(name)) {
                query.setQuery("name_ik: *" + name+"*");
//                根据三级分类id查下面所有商品
            }else if(!StringUtils.isEmpty(classifythree)){
                query.setQuery("classifythree_i:"+classifythree);
            }else if(!StringUtils.isEmpty(classifyone)){
//                一级分类id
                query.setQuery("classifyone_i:"+classifyone);
            }else{
//                查所有
                query.setQuery("*:*");
            }
            if(!StringUtils.isEmpty(currentPage)){
                int currentPages=Integer.parseInt(currentPage);
                page.setCurrentPage(currentPages);

                //计算当前位置
                query.setStart((currentPages-1)*page.getPageSize());
                query.setRows(page.getPageSize());
            }

            //        排序
            query.addSort("price_d", SolrQuery.ORDER.desc);
            qr = solrClient.query(query);

            //分页数据
            proList=qr.getBeans(Products.class);
            logger.debug("ProductsServiceImpl proList proList: "+proList);

//            获取总条数
            SolrDocumentList solrDocuments=qr.getResults();
            logger.debug("ProductsServiceImpl proList name: "+name+" classifythree "+classifythree+" classifyone: "+classifyone+" totalCount："+solrDocuments);
            int totalCount=(int)solrDocuments.getNumFound();
            logger.debug("ProductsServiceImpl proList totalCount: "+totalCount);
            page.setTotalCount(totalCount);


//            存储数据
            page.setList(proList);
        } catch (SolrServerException e) {
            e.printStackTrace();
            logger.debug("ProductsServiceImpl proList name: "+name+" classifythree "+classifythree+" classifyone: "+classifyone+" is error e"+e);
        } catch (IOException e) {
            e.printStackTrace();
            logger.debug("ProductsServiceImpl proList name: "+name+" classifythree "+classifythree+" classifyone: "+classifyone+" is error e"+e);
        }
        return page;
    }



    /**
     * 根据商品id查
     * 用于商品详情展示
     * @param id
     * @return
     */
    @Override
    public List<Products> goodsById(String id) {
        logger.debug("ProductsServiceImpl goodsById id: "+id);
        List<Products> productsList=null;
        SolrQuery query=new SolrQuery();
        QueryResponse qr = null;
        Products products=null;
        try {
            if (!StringUtils.isEmpty(id)) {
                query.setQuery("id:" + id);
            }
            qr = solrClient.query(query);
            productsList=qr.getBeans(Products.class);
            logger.debug("ProductsServiceImpl goodsById id: "+id+" productsList: "+productsList);

        }catch (Exception e){
            e.printStackTrace();
            logger.debug("ProductsServiceImpl goodsById id: "+id+" productsList: "+productsList+" is error ",e);
        }
        return productsList;
    }


    public Products goodsByIdView(String id){
        logger.debug("ProductsServiceImpl goodsByIdView id: "+id+"");
        List<Products> productsList=null;
        SolrQuery query=new SolrQuery();
        QueryResponse qr = null;
        Products products=null;

        try {
            if (!StringUtils.isEmpty(id)) {
                query.setQuery("id:" + id);
            }
            qr = solrClient.query(query);
            productsList=qr.getBeans(Products.class);
            logger.debug("ProductsServiceImpl goodsByIdView id: "+id+" productsList: "+productsList);

            for (Products products1:productsList){
                products=products1;
                logger.debug("ProductsServiceImpl goodsByIdView id: "+id+" productsList: "+productsList+" products: "+products);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("ProductsServiceImpl goodsByIdView id: "+id+" productsList: "+productsList+" products: "+products+" is error ",e);
        }
        return products;
    }



    /**
     * 根据id删除对象
     * @param
     * @return
     */
    @Override
    public String deletePro(String id) throws IOException, SolrServerException {
        logger.debug("ProductsServiceImpl deletePro id： "+id);
        if(null!=id&&!"".equals(id)){
            try {
                UpdateResponse response= solrClient.deleteById(id);
                if(response.getStatus()!=0){
                    logger.debug("ProductsServiceImpl deletePro id： "+id+" is error ");
                    solrClient.rollback();
                }
                solrClient.commit();

            } catch (SolrServerException e) {
                e.printStackTrace();
                solrClient.rollback();
                logger.debug("ProductsServiceImpl deletePro id： "+id+" is error "+e);
            } catch (IOException e) {
                e.printStackTrace();
                solrClient.rollback();
                logger.debug("ProductsServiceImpl deletePro id： "+id+" is error "+e);
            }
        }
        return "200";
    }


    /**
     * 删除所有用于测试
     * @return
     * @throws IOException
     * @throws SolrServerException
     */
    @Override
    public String delView() throws IOException, SolrServerException {
        logger.debug("ProductsServiceImpl delView");
        try {
            UpdateResponse re=solrClient.deleteByQuery("*:*");
            logger.debug("ProductsServiceImpl delView result: "+re);
            if(re.getStatus()!=0){
                logger.debug("ProductsServiceImpl delView is error ");
                solrClient.rollback();
            }
            solrClient.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
            solrClient.rollback();
            logger.debug("ProductsServiceImpl delView is error "+e);
        } catch (IOException e) {
            e.printStackTrace();
            solrClient.rollback();
            logger.debug("ProductsServiceImpl delView is error "+e);
        }
        return "200";
    }

    /*
    添加商品到solr
     */
    @Override
    public String addProductsManage(Products products) {
        logger.debug("ProductsServiceImpl addProductsManage-products:"+products);
        try {
            UpdateResponse result = solrClient.addBean(products);
            logger.debug("ProductsServiceImpl addProductsManage-result："+result);
            if (result.getStatus() != 0) {
                logger.debug("ProductsServiceImpl addProductsManage-is error");
                solrClient.rollback();
            }
            solrClient.commit(false,false,true);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        return "200";
    }


}